<?php

require_once 'ActionFramework/start.php';
require_once 'views/all.cls.php';

require_once 'actions/_user_settings.cls.php';

/**
 * Save the criteria and return to the edit criteria view.
 */
class SavePasswordAction extends _UserSettingsAction {
	
	const INPUT_OLD_PASSWORD = 'old_password';
	const INPUT_CHALLENGE_ID = 'challenge_id';
	
	public function __construct() {
		parent::__construct();
		$this->add_input(new Input(SavePasswordAction::INPUT_OLD_PASSWORD, 'Old password'));
		$this->add_input(LoginAction::INPUT_CHALLENGE_ID);
		$this->add_password_input();
	}
	
	public function trigger($request) {

		$user_password_cocktail = $request[SavePasswordAction::INPUT_OLD_PASSWORD];
		$challenge_id = $request[SavePasswordAction::INPUT_CHALLENGE_ID]; 
		$new_password = $request[SavePasswordAction::INPUT_PASSWORD];
		
		$user = $_SESSION['user'];
		
		global $DB;
		$challenge = $DB->get_challenge($challenge_id);
		if ($challenge !== null) {
			// user password is already hashed with the system salt
			$server_password_cocktail = sha1($user->password.$challenge);
			if ($server_password_cocktail === $user_password_cocktail) {
				$this->update_user(array(User::password => $new_password));
				
				$view = new EditProfileView($user);
				$view->add_message("New password saved");
				return $view;
			}			
		}
		
		// Redirect to change password again
		$view = r(new EditPasswordAction())->trigger($request);
		$view->add_message("The original password was not correct. The password has not been changed.");
		return $view;
		

	}
}

?>